package com.yonyou.hxjy.utils;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class RequestLogAspect {
    private final static Logger LOGGER = LoggerFactory.getLogger(RequestLogAspect.class);

    @Pointcut("execution(* com.yonyou.hxjy.job..*(..))")
    public void requestServer() {
    }

    // @Pointcut("execution(* com.yonyou.wdt.job.abandonment.WdtRefundStockinToYsSaleOutJob..*(..))")
    // public void requestServerSum() {
    // }
    //
    // @Around("requestServerSum()")
    // public Object doAroundSum(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    //     long start = System.currentTimeMillis();
    //     Object result = proceedingJoinPoint.proceed();
    //     RequestInfo requestInfo = new RequestInfo();
    //     requestInfo.setTimeCost(System.currentTimeMillis() - start);
    //     LOGGER.info("旺店通销售退货入库单汇总同步YS销售出库单（红字）任务执行完成，共耗时      : {}毫秒", JSON.toJSONString(requestInfo));
    //     return result;
    // }

    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setTimeCost(System.currentTimeMillis() - start);
        LOGGER.info("任务执行完成，共耗时      : {}毫秒", JSON.toJSONString(requestInfo));
        return result;
    }


    @AfterThrowing(pointcut = "requestServer()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
        requestErrorInfo.setException(e);
        LOGGER.info("Error Request Info      : {}", JSON.toJSONString(requestErrorInfo));
    }

    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            // 如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();  // 获取文件名
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }

    @Data
    public class RequestInfo {
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
        private Object result;
        private Long timeCost;
    }

    @Data
    public class RequestErrorInfo {
        private String ip;
        private String url;
        private String httpMethod;
        private String classMethod;
        private Object requestParams;
        private RuntimeException exception;
    }
}